package com.biubiushop.Socket.TcpAndUdp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * @author chenjia
 * @date 2019/7/16
 **/
public class SocketThread extends Thread {

    Socket socket = null;

    public SocketThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        InputStream bis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            bis = socket.getInputStream();
            isr = new InputStreamReader(bis);
            br = new BufferedReader(isr);
            String info = null;
            while ((info = br.readLine()) != null) {
                System.out.println("服务器接收到客户端的信息:" + info);
            }
            socket.shutdownInput();

            os = socket.getOutputStream();
            osw = new OutputStreamWriter(os);
            bw = new BufferedWriter(osw);
            bw.write("================服务端欢迎您!===================");
            bw.flush();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (osw != null)
                    osw.close();
                if (os != null)
                    os.close();

                if (br != null)
                    br.close();
                if (isr != null)
                    isr.close();
                if (bis != null)
                    bis.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
